
package com.google.code.sms.android.util;

import java.io.File;
import java.io.PrintWriter;

import com.google.code.sms.android.activity.SMSTabActivity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

/**
 * Logs the stack trace of uncaught exceptions to a file on the SD card.
 */
public class SMSUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = SMSTabActivity.class.getSimpleName();

    private final Thread.UncaughtExceptionHandler defaultHandler;
    private final Context context;

    public SMSUncaughtExceptionHandler(Context context) {
        this.context = context;
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void uncaughtException(Thread thread, Throwable throwable) {
        File file = null;
        PrintWriter printWriter = null;
        try {

            PackageInfo packageInfo = context.getPackageManager().getPackageInfo("com.google.code.sms.android", 0);
            file = new File(Environment.getExternalStorageDirectory(), "sms-stacktrace.txt");
            printWriter = new PrintWriter(file);
            printWriter.println("Android API level: " + Build.VERSION.SDK_INT);
            printWriter.println("SMS version name: " + packageInfo.versionName);
            printWriter.println("SMS version code: " + packageInfo.versionCode);
            printWriter.println();
            throwable.printStackTrace(printWriter);
            Log.i(TAG, "Stack trace written to " + file);
        } catch (Throwable x) {
            Log.e(TAG, "Failed to write stack trace to " + file, x);
        } finally {
            Util.close(printWriter);
            if (defaultHandler != null) {
                defaultHandler.uncaughtException(thread, throwable);
            }
        }
    }
}
